#! /Users/Super/py27/bin/python
# -*- coding: utf-8 -*-
# Create by Albert_Chen
# CopyRight (py) 2016年 陈超. All rights reserved by Chao.Chen.
# Create on 2016-11-23
# This script is used for backup monogdb data  daily
# After test mongodumps can create a folder

__author__ = 'Albert'

import os
import datetime
import subprocess

base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
back_dir = 'mongodumps'

def create_dir(base_dir, back_dir, folder):

    base_path = os.path.join(base_dir, back_dir)
    if not os.path.exists(base_path):
        os.mkdir(base_path)
    folder_path = os.path.join(base_path, folder)
    if not os.path.exists(folder_path):
        os.mkdir(folder_path)

def dump_mongodb():
    now = datetime.datetime.now()
    timestamp = now.strftime('%Y%m%d')
    folder = 'dumps_' + timestamp
    file_path = os.path.join(base_dir, back_dir, folder)
    create_dir(base_dir, back_dir, folder)
    proc = subprocess.Popen(['mongodump', '--out', file_path])
    (out, err) = proc.communicate()
    if not err:
        print "backup mongodb success at folder %s" %file_path
if __name__ == "__main__":

    dump_mongodb()